//importing javascipt core modules
Components.utils.import("resource://downloadextender/common.js");
Components.utils.import("resource://downloadextender/downloadextender.js");

if ("undefined" == typeof(downloadextender)) {
  var downloadextender = {};
};

downloadextender.preferencewindow = {
  onsave: function() {	
    try {
	  if (document.getElementById("downloadextenderdetectallcheck")) {
	    let checked = document.getElementById("downloadextenderdetectallcheck").getAttribute("checked");
	    downloadextender.pref.savedetectall(checked);
	  }
	  
	  //updates checkbox of mainwindow if present
      if (downloadextender.mainwindow != null) { downloadextender.mainwindow.refreshlistencheckbox(); }
	
      let newfilterlist = [];  
	  let tree = document.getElementById("downloadextenderfilterTable");		
	
	  //makes sure filters are only updated when filterpanel was loaded
      if (tree) {
	    for (var i = 0; i < tree.view.rowCount; i++) { 
	      let newfilter = {};
	      newfilter.enabled = escape(tree.view.getCellValue(i, tree.columns.getColumnAt(0)));
	      newfilter.description = escape(tree.view.getCellText(i, tree.columns.getColumnAt(1)));
	      newfilter.contenttype = escape(tree.view.getCellText(i, tree.columns.getColumnAt(2)));
	      newfilter.targetdirectory = escape(tree.view.getCellText(i, tree.columns.getColumnAt(3)));
          newfilterlist.push(newfilter);
	    }
	    let filters = JSON.stringify(newfilterlist);
	    downloadextender.pref.savefilters(filters);
	  }
	
      let newblacklist = [];  
	  let blacklisttree = document.getElementById("downloadextenderblacklistTable");		

	  //makes sure blacklist is only updated when blacklistpanel was loaded
      if (blacklisttree) {
	    for (var i = 0; i < blacklisttree.view.rowCount; i++) { 
	      let newfilter = {};
	      newfilter.enabled = escape(blacklisttree.view.getCellValue(i, blacklisttree.columns.getColumnAt(0)));
	      newfilter.description = escape(blacklisttree.view.getCellText(i, blacklisttree.columns.getColumnAt(1)));
	      newfilter.URL = escape(blacklisttree.view.getCellText(i, blacklisttree.columns.getColumnAt(2)));	   
          newblacklist.push(newfilter);
	    }
	    let blacklist = JSON.stringify(newblacklist);
	    downloadextender.pref.saveblacklist(blacklist);
	  }	
    }
	catch (e) { downloadextender.consoleService("onsave: "+e); }
	}

}